package org.example.java.util.concurrency.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by juntaozhang on 3/16/15.
 */
public class AtomicIntegerDemo {
  AtomicInteger number= new AtomicInteger(0);
  class Task extends Thread {

    @Override
    public void run() {
      System.out.println(number.addAndGet(1));
      Thread.yield();
      System.out.println(number.addAndGet(1));
    }
  }
  public static void main(String[] args) {
    AtomicIntegerDemo demo = new AtomicIntegerDemo();
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 100; i++)
      exec.execute(demo.new Task());
    try {
      TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    exec.shutdown();
    System.out.println("================");
    System.out.println(demo.number);
  }
}
